Java From Zero: Learn Java Programming Fast for Beginners to Professionals: The Complete Guide With Code Examples and Exercises to Become a Professional by Scott Brandt

Java From Zero: Learn Java Programming Fast for Beginners to Professionals: The Complete Guide With Code Examples and Exercises to Become a Professional by Scott Brandt

Author:Scott Brandt [Brandt, Scott]
Language: eng
Format: epub
Publisher: UNKNOWN
Published: 2023-02-11T00:00:00+00:00


Implementing Polymorphism in Java and its Relation to Inheritance

Polymorphism in Java establishes that a method can be executed in different forms. Suppose you have the interface "geometric figure." When you have this situation, you are referring to all geometric figures, and you will implement methods that enable you to calculate their different areas. This means you will have the "square method," "circle method," "triangle method," and so on. This means that the class will still be the same, but the way each of the methods behaves is different because each geometric figure will be calculated distinctly.

Polymorphism is directly related to inheritance since it will enable the inheritance of the attributes and methods from another class. When you apply polymorphism to this, you are using these methods to perform different tasks, enabling you to do the same thing in different ways.

Pro tip: When you use the word "final" at the end of methods and classes, you are declaring that they cannot be reimplemented or extended. For example, all of those pertaining to the String method and even the String classes are considered final.

class GeometricFigure{ public void shapeColor() {

System.out.println("The figure is");

}

} class Square extends GeometricFigure {

public void shapeColor() {

System.out.println("The square is red"); }

}

class Circle extends GeometricFigure { public void shapeColor() {

System.out.println("The circle is blue");

} }

public class Main {

public static void main(String[] args) { GeometricFigure mySquare = new Square(); // Create a Square object

GeometricFigure myCircle = new Circle(); // Create a Circle object

mySquare.shapeColor(); myCircle.shapeColor();

} The output for this program will be:

The square is red

The circle is blue As you will see, we have created two different shape colors, one for the square and red, and one for the circle and blue.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.